<template>
<!-- 关联销售单--新增关联销售单 组件 -->
  <div>
    <zm-dialog
      title="添加"
      :visible.sync="value"
      append-to-body
      :before-close="dialogClose"
      size="large"
    >
      <div class="pd15">
        <zm-form :model="form" :rules="formRules" ref="formRef">
           <zm-form-item prop="orderNo" label="关联销售单号:">
            <zm-input
                v-model="form.orderNo"
                placeholder="请输入销售单号"
                class="w200"
            ></zm-input>
            <zm-button>验证</zm-button>
            <zm-button @click="add" :disabled="form.arr.length >= 9">新增</zm-button>
           </zm-form-item>
            <zm-form-item v-for="(item,index) in form.arr" :key="index" prop="orderNo" class="ml95">
            <zm-input
                v-model="item.orderNo"
                placeholder="请输入销售单号"
                class="w200"
            ></zm-input>
            <zm-button>验证</zm-button>
            <zm-button @click="del(item,index)">删除</zm-button>
           </zm-form-item>
</zm-form>
      </div>
      <template v-slot:footer class="tr">
        <el-button @click="myCancel">取消</el-button>
        <el-button @click="submit('formRef')" type="primary">确定</el-button>
      </template>
    </zm-dialog>
  </div>
</template>
<script>
import dialogMixin from '@/mixins/dialogMixin'
import {saleOrderVerify, saleOrderBind} from '@/api/src/sendCouponSet'
export default {
  name: 'AddDialog',
  mixins: [dialogMixin],
  props: {
    id: {
      type: String,
      required: true
    }
  },
  data () {
    var validateSaleOrder = async (rule, value, callback) => {
      try {
        await saleOrderVerify({orderNo: value, type: '2'})
        this.$message.success('验证通过!')
      } catch (err) {
        callback(new Error(err.content))
      }
    }
    return {
      form: {
        orderNo: '',
        arr: []
      },
      formRules: {
        orderNo: [
          { validator: validateSaleOrder, trigger: 'blur' }
        ]
      }
    }
  },
  computed: {

  },
  created () {
    this.init()
  },
  methods: {
    init () {
    },
    add () {
      this.form.arr.push({orederNo: ''})
    },
    del (index) {
      this.form.arr.splice(index, 1)
    },
    async submit (formRef) {
      this.$refs[formRef].validate(async (valid) => {
        if (valid) {
          let orderNo = []
          this.form.arr.forEach((item) => {
            return orderNo.push(item.orderNo)
          })
          orderNo.unshift(this.form.orderNo)
          await saleOrderBind({programId: this.id, orderNo: orderNo.join()})
          this.$emit('refresh')
          this.myCancel()
        } else {
          this.$message.error('绑定失败！')
        }
      })
    },
    myCancel () {
      this.$emit('input', false)
    }
  }
}
</script>
